package biz.inspeed.test.concurrent;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Producer_Consumer {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		BlockingQueue<String> data = new ArrayBlockingQueue<String>(10);
		new Thread(new Producer(data)).start();
		new Thread(new Producer(data)).start();
		
		new Thread(new Consumer(data)).start();
		new Thread(new Consumer(data)).start();
	}

}

class Producer implements Runnable{
	private BlockingQueue<String> data;
	
	public Producer(BlockingQueue<String> data){
		this.data = data;
	}

	@Override
	public void run() {
		try {
			while(true){
				data.offer(produce());
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private String produce(){
		SimpleDateFormat format = new SimpleDateFormat("HH-mm-ss-SSS");
		String string = format.format(new Date());
		string = Thread.currentThread().getName() + "---" + string;
		return string;
	}
}


class Consumer implements Runnable{
	private BlockingQueue<String> data;
	
	public Consumer(BlockingQueue<String> data){
		this.data = data;
	}

	@Override
	public void run() {
		try{
			while(true){
				consume(data.take());
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}		
	}
	
	private void consume(String str){
		SimpleDateFormat format = new SimpleDateFormat("HH-mm-ss-SSS");
		String string = format.format(new Date());
		string = Thread.currentThread().getName() + "---" + string;
		System.out.println(string + "------" + str);
	}
}
